<?php
/*+--------------------------------------------------------------------
 * 作	  者: hemm <1429655840@qq.com>
 +----------------------------------------------------------------------
 * 创建日期：2015-07-08
 +----------------------------------------------------------------------
 * 文件描述：成员管理
 +----------------------------------------------------------------------
 * 升级记录：songyb整理优化功能（2015-07-08）
 *		weilp整理用户导入及用户主键生成
 +----------------------------------------------------------------------
*/
header("Content-Type:text/html;Charset=utf-8");
class GroupsUserAction extends CommonAction {
	/**
	 * 成员管理
	 */
	
	public function index() {
		$model = new GroupsUserModel();
		$groupsid = $_REQUEST['groupsid'];
   		//条件检索
		if(!empty($_REQUEST['search_keyword'])) {
			$where['name|real_name|professional|phone|email'] = array('like', '%'.$_REQUEST['search_keyword'].'%');
		}
		//通过省市县检索
		if(!empty($_REQUEST['school'])) {
			$where['school'] = $_REQUEST['school'];
		} elseif(!empty($_REQUEST['area_code'])) {
			$where['area_code'] = $_REQUEST['area_code'];
		} elseif(!empty($_REQUEST['city_code'])) {
			$where['area_code'] = array('like', $_REQUEST['city_code'].'%');
		} elseif(!empty($_REQUEST['province_code'])) {
			$where['area_code'] = array('like', $_REQUEST['province_code'].'%');
		}
		if(!empty($_REQUEST['type'])) {
			$where['type'] = $_REQUEST['type'];
		}
//		dump($where);
//		dump($_REQUEST);
//		exit;
		
		$where['groupsid'] = $groupsid;
		//分页处理
		import('ORG.Util.Page');// 导入分页类
		$count = $model->where($where)->count();  // 查询满足要求的总记录数
		
		$p = $this->_page($model, 'id');  //分页所需信息
		$page = new Page($count, $p['listRows']);  // 实例化分页类 传入总记录数和每页显示的记录数
		
 		$data = $model->field("id,
 							   groupsid,
 							   name,
 							   real_name,
 							   get_field_dict_name('groups_user', 'type', type) type,
 							   get_field_dict_name('user', 'gender', gender) gender,
 							   area_code,
 							   get_area_name(area_code) area_name,
 							   get_school_name(school) school,
 							   get_field_dict_name('groups_user','school_type',school_type) school_type,
 							   get_item_num(id) item_num,
 							   get_item_num_total(id) value_num,
 							   get_formate_time(begin_time) begin_time,
 							   get_formate_time(end_time) end_time,
 							   time_format(timediff(end_time, begin_time),'%H:%i:%s') used_time,
 							   feedback,
 							   get_user_name(operator) operator,
							   get_formate_date(update_date) update_date")  
 					  ->where($where)
 					  ->order("`".$p['order']."` ".$p['sort'])
					  ->limit($page->firstRow.', '.$page->listRows)		 
				 	  ->select();
		//dump($data);
		//dump($model->_sql());
		$this->assign('data', $data);
		$show = $page->show();	//分页显示输出
		$this->assign('show', $show);	//绑定分页显示字符串
		$this->assign('groupsid', $groupsid);
		$this->assign('type_list', set_field_dict_list('groups_user', 'type'));
		
		$this->assign('province_list', get_province_list());	//省份列表
		//查询该省份下的市州列表
		if(!empty($_REQUEST['province_code'])) {
			$model = new CityModel();
			$city_list = $model->field("code, name")
							   ->where("province_code = '".$_REQUEST['province_code']."'")
							   ->select();
			$this->assign('city_list', $city_list);
		}
		//查询该市州下的县区列表
		if(!empty($_REQUEST['city_code'])) {
			$model = new AreaModel();
			$area_list = $model->field("code, name")
							   ->where("city_code = '".$_REQUEST['city_code']."'")
							   ->select();
			$this->assign('area_list', $area_list);
		} 
		//查询该县域下的学校列表
		if(!empty($_REQUEST['area_code'])) {
			$model = new SchoolModel();
			$school_list = $model->field("id, name")
								 ->where("area_code = '".$_REQUEST['area_code']."'")
								 ->select();
			$this->assign('school_list', $school_list);
		} else {
			$model = new SchoolModel();
			$school_list = $model->field("id, name")
								 ->select();
			$this->assign('school_list', $school_list);
		}
		$this->display();
	}
	
	/**
	 * 添加成员
	 */
	public function add() {
		$this->assign('province_list', get_province_list());	//省份列表
		$this->assign('gender_list', set_field_dict_list('user', 'gender'));
		//$this->assign('professional_list', set_field_dict_list('groups_user', 'professional'));
		//$this->assign('status_list', set_field_dict_list('user', 'status'));
		$this->display();
	}
	
	/**
	 * 将用户信息添加至数据库
	 */
	public function insert() {
		$groupsid = $_REQUEST['groupsid'];
		//$data = $this->_request();
		$model = new GroupsUserModel();
		
		$phone = $_REQUEST['phone'];
		$pwd = substr($phone, -6);
		$_POST['pwd']=md5($pwd);
		//dump($pwd);exit;
		
		$data = $model->create();
		//dump($data);
		$id = $model->add($data);
		if(false !== $id) {
			$this->success("添加成功", __APP__.'?g=Admin&m=GroupsUser&a=index&groupsid='.$groupsid);
		} else {
			$this->error("添加失败");
		}
	}
	
	/**
	 * 修改用户信息页面显示
	 */
	public function edit() {
		//查询当前用户信息
		$groupsid = $_REQUEST['groupsid'];
		$model = new GroupsUserModel();
		$data = $model->where("id = '".$_REQUEST['id']."'")->find();
		if(empty($data)) {
			$this->error('未找到您要修改的用户信息！');
		}
		$this->assign('data', $data);
		//数据字典信息绑定
		$this->assign('gender_list', set_field_dict_list('user', 'gender'));
		//$this->assign('professional_list', set_field_dict_list('groups_user', 'professional'));
		//$this->assign('status_list', set_field_dict_list('user', 'status'));
		$this->display();
	}
	
	/**
	 * 更新用户信息至数据库
	 */
	public function update() {
		$groupsid = $_REQUEST['groupsid'];
		$data = $this->update_user($this->_request(), $msg);
		if(false !== $data) {
			redirect(__APP__.'?g=Admin&m=GroupsUser&a=index&groupsid='.$groupsid);
		} else {
			$this->error($msg);
		}
	}
  
	/**
	 * 删除用户信息
	 */
	public function delete() {
		$userIds = $this->_request('ids');
		if(false !== $this->delete_user($userIds, $msg)) {
			redirect($_SERVER['HTTP_REFERER']);
		} else {
			$this->error($msg);
		}
	}
	
	/**
	 * 添加用户【供其他模块调用】
	 */
	public function add_user($post_data, &$msg) {
		$model = new GroupsUserModel();
		if(!empty($post_data['pwd'])) {
			$post_data['pwd'] = md5($post_data['pwd']);
		}
		if(false !== $model->create($post_data, 1)) {
			$insertId = $model->add();
			if(false !== $insertId) {
				$msg = '用户添加成功！';
				return $insertId;
			} else {
				$msg = '用户添加失败！';
				return false;
			}
		} else {
			$msg = '用户添加失败！'.$model->getError();
			return false;
		}
	}
	
	/**
	 * 更新用户【供其他模块调用】
	 * @param unknown $post_data
	 * @param unknown $msg
	 */
	public function update_user($post_data, &$msg) {
		$model = new GroupsUserModel();
		//对密码字段作特殊处理
		if(!empty($post_data['pwd'])) {
			$post_data['pwd'] = md5($post_data['pwd']);
		} else {
			unset($post_data['pwd']);
		}
		if(false !== $model->create($post_data, 0)) {
			if(false !== $model->save()) {
				$msg = '用户修改成功！';
				return true;
			} else {
				$msg = '用户修改失败！';
				return false;
			}
		} else {
			$msg = '用户修改失败！'.$model->getError();
			return false;
		}
	}
	
	/**
	 * 删除用户【供其他模块调用】
	 * @param array $userIds
	 * @param string &$msg
	 * @return boolean
	 */
	public function delete_user($userIds, &$msg) {
		if(!empty($userIds) && is_array($userIds)) {
			$model = new GroupsUserModel();
			$model->startTrans();
			$id = implode("','", $userIds);	//用','分割id数组，以便于拼装sql语句
			$id = "'".$id."'";	//拼装sql语句，结果为'firstId','secondId',…
			if(false !== $model->where("id in(".$id.")")->delete()) {
				$msg = '用户删除成功！';
				$model->commit();
				return true;
			} else {
				$msg = '用户删除失败！';
				$model->rollback();
				return false;
			}
		} else {
			$msg = '您未选中任何记录！';
			return false;
		}
	}
	
	/**
	 * 清除用户提交问卷数据
	 */
	public function clear_item_value() {
		$id = $this->_request('id');
		$groupsid = $this->_request('groupsid');
		
		$model = new ItemValueModel();
		$groups_user = new GroupsUserModel();
		$clear_data['begin_time'] = null;
		$clear_data['end_time'] = null;
		$clear_data['feedback'] = null;
		$clear_data['page'] = 0;
		if(false === $model->where("operator = '".$id."'")->delete() || 
		   false === $groups_user->where("id = '".$id."'")->save($clear_data)) {
			$this->error('用户提交问卷数据清除失败！');
		} else {
			$this->success('用户提交问卷数据清除成功，可通知用户再次提交数据。');
		}
	}
	
	/**
	 * 通过Validform框架实时验证【用户名】的唯一性
	 * ajaxurl指定的文件可以接收到Post过来的两个值，分别是param和name，param是该元素的值，name是该元素的name名称。可以通过区别name来把一个表单下，多个实时验证请求，都指定到同一个文件。
	 */
	public function check_username() {
		if(!empty($_REQUEST['userid'])) {
			$where['_string'] = "id <> '".$_REQUEST['userid']."'";	//此条件用于修改用户信息时用户名查重检测（查重时忽略本身的用户名）
		}
		$where['name'] = $_REQUEST['param'];
		
		$model = new GroupsUserModel();
		$userid = $model->where($where)->getField('id');
		//若数据库中该用户名不存在，则该用户名可以使用
		if(empty($userid)) {
			echo 'y';	//Validform实时验证成功时只能输出'y'，其它任何字符将作为验证失败提示信息返回
		} else {
			echo '该用户名已经存在，请选择其他！';
		}
	}
	
	/**
	 * 重置密码
	 */

 	public function resetpwd() {
		$id = $this->_request('id');
		$this->assign("id", $id);	// 未处理之前重新绑定，需传递到下一个提交的地址
		
		$model = new GroupsUserModel();
		$pwd = $model->where("id = '".$id."'")->getField("phone");
		$pwd = substr($pwd, -6);
		if(empty($pwd)) {
			$pwd = C('default_pwd');
		}
		$this->assign('pwd', $pwd);
		$this->display();
		
	}
	
	/**
	 * 重置密码保存
	 */
	public function resetpwd_save() {
		$id = $this->_request('id');
		$pwd = $this->_request('pwd');
		$model = new GroupsUserModel();
		if(false === $model->where("id = '".$id."'")->setField('pwd', md5($pwd))) {
			$this->error('重置失败');
		} else {
			$this->success('重置成功，新密码为：'.$pwd);
		}
	}
	/*
 *	 * 导入界面
	 * 
	 * */
	public function import() {
		$head_array = C('PLDR_GROUPS_USER_EXCEL_HEAD');
		$this->assign('head_string', implode(',', $head_array));
		$this->display();
	}
	
	//用户导入（操作）
	public function importDo() {
		$groupsid = $_REQUEST['groupsid'];
		$model = new GroupsUserModel();
		import("ORG.Net.UploadFile");
		if(!empty($_FILES['xls']['name'])){
			$upload = new UploadFile();// 实例化上传类
			$upload -> maxSize = -1;// 设置附件上传大小，-1无限制大小
		   	$upload -> savePath = C('PLDR_UPLOAD_PATH').$model ->getWebId().C('PLDR_AFFIX_PATH');
		  	$upload -> allowExts = C('PLDR_XLS_ALLOWEXTS');
			$upload -> saveRule = uniqid; //设置上传文件的保存规则
			if(!($info = $upload->uploadOne($_FILES['xls'], $upload->savePath))) { // 上传错误 提示错误信息
		   		$this->error('操作失败：文件上传错误！'.$upload->getErrorMsg());
			} else {
				$memory_limit = ini_get("memory_limit");
				ini_set("memory_limit ", C('MEMORY_LIMIT'));
				$file = $info[0]['savepath'].$info[0]['savename'];
				$xls_data = $this->importExecl($file);
				$data = $xls_data['data'][0]['Content'];
				
				//检测头部是否符合要求
				$count = $xls_data['data'][0]['Cols'];
			
				$head_array = C('PLDR_GROUPS_USER_EXCEL_HEAD');
				if($count != count($head_array)) {
					$this->error("表中列的个数为".$count."列,与要求的".count($head_array)."列不符，请核对后再导入,请务必保证在表格中不要使用公式和函数！");
				}
				$head_xls = $data[1];
				foreach ($head_array as $key => $row) {
					if($row != str_replace(' ', '', $head_xls[$key])) {
						$this->error("表中列名“".$head_xls[$key]."”与要求的“".$row."”不一致，请核对后再导入,请务必保证在表格中不要使用公式和函数！");
					}
				}
				array_shift($data);  //去掉头部
				$this->assign("");
 				//修改键值
				$head_xls = array_flip($head_xls);
				array_unshift($data,$head_xls);
				array_shift($data);
				$new_no = 0;
				$exits_no = 0;
				$area_code = '';
				
				//开启事务
				$model->startTrans();
				foreach ($data as $key => $row) {
					if(empty($temp_data)) {
						//$sql_data['id'] = $row[0]; 
						//$sql_data['groupsid'] = $row[1];
						$sql_data['name'] = $row[0];
						//$sql_data['pwd'] = md5(substr($row[3], -6));
						$sql_data['real_name'] = $row[1];
						// 匹配性别
						$gender = 'a';
						if(strpos(' '.$row[2], '男') > 0) {
							$gender = 'a';
						} elseif(strpos(' '.$row[2], '女') > 0) {
							$gender = 'b';
						} 
						$sql_data['gender'] = $gender;
						$sql_data['professional'] = $row[3];
						$sql_data['duty'] = $row[4];
						$sql_data['certificate_no'] = $row[5];
						$sql_data['phone'] = $row[6];
						$sql_data['pwd'] = md5(substr($sql_data['phone'],-6));
						$sql_data['email'] = $row[7];
						$sql_data['groupsid'] = $groupsid;
						$sql_data['operator'] = $model->getuserId();
						$sql_data['update_date'] = $model->getShortDate();
						if(false === $model->add($sql_data)) {
							$model->rollback();
							$this->error('导入失败1：'.$model->getDbError());
						}
						unset($sql_data);
					}
				}
				//提交事务
				$model->commit();				
				ini_set("memory_limit", $memory_limit);
				$this->success("导入成功，此次导入".($xls_data['data'][0]['Rows']-1)."条记录。",__APP__.'?g=Admin&m=GroupsUser&a=index&groupsid='.$groupsid);
			}
		} else {
			$this->error("请选择您要导入的文件");
		}
	}
	
	/**
	 * 导入数据
	 * 
	 * */
	public function importExecl($file){ 
		if(!file_exists($file)){ 
			return array("error" =>0,'message'=>'file not found!');
		} 
		Vendor("PHPExcel.IOFactory"); 
		$objReader = PHPExcel_IOFactory::createReader('Excel5');
		try{
			$PHPReader = $objReader->load($file);
		}catch(Exception $e){}
		if(!isset($PHPReader)) return array("error"=>0,'message'=>'read error!');
		$allWorksheets = $PHPReader ->getAllSheets();
		$i = 0;
		foreach($allWorksheets as $objWorksheet){
			$sheetname = $objWorksheet ->getTitle();
			 
			$allRow = $objWorksheet->getHighestRow();//how many rows
			
			$highestColumn = $objWorksheet->getHighestColumn();//how many columns
			
			$allColumn = PHPExcel_Cell::columnIndexFromString($highestColumn);
		  
			$array[$i]["Title"] = $sheetname; 
			$array[$i]["Cols"] = $allColumn;
			$array[$i]["Rows"] = $allRow; 
			$arr = array();
			$isMergeCell = array();
			foreach ($objWorksheet->getMergeCells() as $cells) {//merge cells
				foreach (PHPExcel_Cell::extractAllCellReferencesInRange($cells) as $cellReference) {
					$isMergeCell[$cellReference] = true;
				}
			}
			for($currentRow = 1; $currentRow <= $allRow; $currentRow++){ 
				$row = array(); 
				for($currentColumn = 0; $currentColumn < $allColumn; $currentColumn++){;				
					$cell = $objWorksheet->getCellByColumnAndRow($currentColumn, $currentRow);
					$afCol = PHPExcel_Cell::stringFromColumnIndex($currentColumn+1);
					$bfCol = PHPExcel_Cell::stringFromColumnIndex($currentColumn-1);
					$col = PHPExcel_Cell::stringFromColumnIndex($currentColumn);
				   // echo $cell;
					$address = $col.$currentRow;
					$value = $objWorksheet->getCell($address)->getValue();
					if(substr($value,0,1) == '='){
						return array("error" =>0,'message' =>'can not use the formula!');
						exit;
					} 
					if($isMergeCell[$col.$currentRow]&&$isMergeCell[$afCol.$currentRow]&&!empty($value)){
						$temp = $value;
					}elseif($isMergeCell[$col.$currentRow]&&$isMergeCell[$col.($currentRow-1)]&&empty($value)){
						$value=$arr[$currentRow-1][$currentColumn];
					}elseif($isMergeCell[$col.$currentRow]&&$isMergeCell[$bfCol.$currentRow]&&empty($value)){
						$value=$temp;
					}
					$row[$currentColumn] = $value; 
					
				} 
				$arr[$currentRow] = $row; 
			} 
			$array[$i]["Content"] = $arr; 

			$i++;
		}
		spl_autoload_register(array('Think','autoload'));//must, resolve ThinkPHP and PHPExcel conflicts
		unset($objWorksheet); 
		unset($PHPReader); 
		unset($PHPExcel); 
		unlink($file); 
		return array("error"=>1,"data"=>$array); 
	}
	
	/**
	 * 生成主键字段
	 */
	public function generate_primarykey($groups_userkey_left,&$groups_userkey_right){
		if(!empty($groups_userkey_right)) {
		$groups_userkey_right = (int)$groups_userkey_right['id'] + 1;
	   		switch (strlen($groups_userkey_right)) {
				case 1:
					return $groups_userkey_left.'00000'.$groups_userkey_right;
		   		case 2:
	   				return $groups_userkey_left.'0000'.$groups_userkey_right;
		   		case 3:
		   			return $groups_userkey_left.'000'.$groups_userkey_right;
		   		case 4:
		   			return $groups_userkey_left.'00'.$groups_userkey_right;
		   		case 5:
		   			return $groups_userkey_left.'0'.$groups_userkey_right;
		   		case 1:
		   			return $groups_userkey_left.$groups_userkey_right;
	   		}
		} else {
			return $groups_userkey_left.'000001';
		} 		
	}
	
	/**
	 * 批量下载用户问卷详细数据
	 */
	public function download_bat() {
		$user_type = $this->_request('type');
		$objid = $this->_request('objid');
		$this->download_detail($user_type, $objid);
	}
	
	/**
	 * 下载问卷详细数据
	 * @param string $user_type 用户类型
	 * @param string $objid 范围对象编号，学生、教师、校管：学校编号，县管：县域代码
	 * @param string $groups_userid 用户编号
	 */
	public function download_detail($user_type, $objid, $groups_userid = null) {
		set_time_limit(0);
		$formid = get_system_option("问卷".$user_type);
		//查询问卷信息
		$form = new FormModel();
		$form_data = $form->field("title,
								   item_info")
						  ->where("id = '".$formid."'")
						  ->find();
		$question_array = explode(",", $form_data['item_info']);
//		dump($item_array);
		//查询用户
		$groups_user = new GroupsUserModel();
		if(empty($user_type)) {
			$this->error("没有找到用户类型");
		}
		if(empty($objid)) {
			$this->error("范围编号不能为空");
		}
		switch ($user_type) {
			case 'a':
			case 'b':
			case 'c':
				$where['school'] = $objid;
				break;
			case 'd':
				$where['area_code'] = $objid;
				break;
			default:
				$this->error("错误的用户类型");
		}
		$where['type'] = $user_type;
		if(!empty($groups_userid)) {
			$where['id'] = $groups_userid;
		}
		$user_data = $groups_user->field("id,
										  type,
										  get_field_dict_name('groups_user','type',type) type_name,
										  name,
										  real_name,
 							   			  get_field_dict_name('user', 'gender', gender) gender,
										  birth,
										  area_code,
										  get_area_name(area_code) area_name,
										  school,
										  get_school_name(school) school_name,
										  get_field_dict_name('groups_user','school_type',school_type) school_type,
										  get_field_dict_name('groups_user','phase',phase) phase,
										  get_field_dict_name('groups_user','grade',grade) grade,
										  get_class_name(class) class_name,
										  get_field_dict_name('groups_user','subject',subject) subject,
										  get_field_dict_name('groups_user','teach_year',teach_year) teach_year,
										  page,
			 							  get_item_num(id) item_num,
			 							  get_item_num_total(id) value_num,
			 							  get_formate_time(begin_time) begin_time,
			 							  get_formate_time(end_time) end_time,
			 							  time_format(timediff(end_time, begin_time),'%H:%i:%s') used_time,
			 							  feedback")
								 ->where($where)
								 ->select();
//		dump($where);
//		dump($user_data);
//		exit;
		//添加表头
		$head = array();   //表头数组
		$detail = array();     //问卷数据
		$detail[0]['name'] = "用户名";
		$detail[0]['real_name'] = "真实姓名";
		$detail[0]['gender'] = "性别";
		switch($user_type) {
			case 'a':
				$detail[0]['birth'] = "出生年月";
				$detail[0]['area_code'] = "所属县域";
				$detail[0]['school'] = "所在学校";
				$detail[0]['school_type'] = "学校类型";
				$detail[0]['phase'] = "学段";
				$detail[0]['grade'] = "年级";
				$detail[0]['class_name'] = "班级";
				break;
			case 'b':
				$detail[0]['birth'] = "出生年月";
				$detail[0]['area_code'] = "所属县域";
				$detail[0]['school'] = "所在学校";
				$detail[0]['school_type'] = "学校类型";
				$detail[0]['teach_year'] = "教龄";
				$detail[0]['phase'] = "学段";
				$detail[0]['subject'] = "教授学科";
				$detail[0]['grade'] = "教授年级";
				$detail[0]['class_name'] = "教授班级";
				break;
			case 'c':
				$detail[0]['area_code'] = "所属县域";
				$detail[0]['school'] = "所在学校";
				$detail[0]['school_type'] = "学校类型";
				break;
			case 'd':
				$detail[0]['area_code'] = "所属县域";
				break;
		}
		$detail[0]['item_num'] = "提交题项数量";
		$detail[0]['value_num'] = "提交信息数量";
		$detail[0]['begin_time'] = "开始时间";
		$detail[0]['end_time'] = "结束时间";
		$detail[0]['used_time'] = "所用时间";
		$detail[0]['feedback'] = "反馈";
		foreach ($question_array as $q_key => $q_value) {
			$temp_question = explode(":", $q_value);
//			dump($temp_item);
			$questionid = $temp_question[1];
			$question_data = $form->table("question_test_select")
								   ->field("code,
								   			question title")
								   ->where("id = '".$questionid."'")
								   ->union("select code, question title from blank where id = '".$questionid."'")
								   ->union("select code, title from affix where id = '".$questionid."'")
								   ->find();
			$question_data['title'] = $this->cutstr_html($question_data['title'], 100);
//			dump($question_data);
			if(!empty($questionid)) {
				$head[$questionid] = '['.$question_data['code'].']'.str_replace('‍‍', '', $question_data['title']);
				$detail[0][$questionid] = str_replace('​', '', str_replace('‍', '', $head[$questionid]));
			}
		}
//		dump($head);
//		exit;
//		dump(chr(33));
//		dump($detail);
//		exit;
		//组装问卷提交数据
		$item_value = new ItemValueModel();
		foreach ($user_data as $u_key => $u_value) {
			$detail[$u_key + 1]['name'] = $u_value['name'];
			$detail[$u_key + 1]['real_name'] = $u_value['real_name'];
			$detail[$u_key + 1]['gender'] = $u_value['gender'];
			switch($user_type) {
				case 'a':
					$detail[$u_key + 1]['birth'] = $u_value['birth'];
					$detail[$u_key + 1]['area_code'] = $u_value['area_code'].' '.$u_value['area_name'];
					$detail[$u_key + 1]['school'] = $u_value['school_name'];
					$detail[$u_key + 1]['school_type'] = $u_value['school_type'];
					$detail[$u_key + 1]['phase'] = $u_value['phase'];
					$detail[$u_key + 1]['grade'] = $u_value['grade'];
					$detail[$u_key + 1]['class_name'] = $u_value['class_name'];
					break;
				case 'b':
					$detail[$u_key + 1]['birth'] = $u_value['birth'];
					$detail[$u_key + 1]['area_code'] = $u_value['area_code'].' '.$u_value['area_name'];
					$detail[$u_key + 1]['school'] = $u_value['school_name'];
					$detail[$u_key + 1]['school_type'] = $u_value['school_type'];
					$detail[$u_key + 1]['teach_year'] = $u_value['teach_year'];
					$detail[$u_key + 1]['phase'] = $u_value['phase'];
					$detail[$u_key + 1]['subject'] = $u_value['subject'];
					$detail[$u_key + 1]['grade'] = $u_value['grade'];
					$detail[$u_key + 1]['class_name'] = $u_value['class_name'];
					break;
				case 'c':
					$detail[$u_key + 1]['area_code'] = $u_value['area_code'].' '.$u_value['area_name'];
					$detail[$u_key + 1]['school'] = $u_value['school_name'];
					$detail[$u_key + 1]['school_type'] = $u_value['school_type'];
					break;
				case 'd':
					$detail[$u_key + 1]['area_code'] = $u_value['area_code'].' '.$u_value['area_name'];
					break;
			}
			$detail[$u_key + 1]['item_num'] = $u_value['item_num'];
			$detail[$u_key + 1]['value_num'] = $u_value['value_num'];
			$detail[$u_key + 1]['begin_time'] = $u_value['begin_time'];
			$detail[$u_key + 1]['end_time'] = $u_value['end_time'];
			$detail[$u_key + 1]['used_time'] = $u_value['used_time'];
			$detail[$u_key + 1]['feedback'] = $u_value['feedback'];
//			dump($detail);
//			exit;
			foreach ($head as $h_key => $h_value) {
				$value = $item_value->field('get_item_value(get_questionid(itemid), operator) value')->where("formid = '".$formid."' and get_questionid(itemid) = '".$h_key."' and operator = '".$u_value['id']."'")->find();
				if(!empty($value)) {
					$detail[$u_key + 1][$h_key] = str_replace(' ', '', $value['value']);
				} else {
//					$detail[$u_key + 1][$h_key] = '***'.$item_value->_sql();
					$detail[$u_key + 1][$h_key] = '';
				}
			}
		}
		
//		dump($detail);
//		exit;
		$file_name = $user_data[0]['type_name'].'问卷提交详细情况';      	//excel文件名
		
		//将用户信息组装成表格导出到excel中
		$str = '';	//初始化
		//输出表头
		$str .= iconv("UTF-8","GBK",'<table border="1">');
//		$str .= iconv("UTF-8","GBK",'<table border="1"><tr><td colspan="'.count($detail[0]).'" align="center" style="font-size:16px; height:32px; font-weight:bold">'.$file_name.'</td></tr>');
		//循环输出行		
		foreach($detail as $v1) {
			$str .= iconv("UTF-8","GBK",'<tr>');
			//循环输出列
//			dump($v1);
//			exit;
			foreach($v1 as $v2) {
				$temp_str = '<td style="vnd.ms-excel.numberformat:@">'.$v2.'</td>';
				$str .= iconv("UTF-8","GBK",$temp_str);
//				dump($v2);
			}
			$str .= iconv("UTF-8","GBK",'</tr>');
//			dump($str);
//			exit;
		}
		$str .=	iconv("UTF-8","GBK",'</table>');
		//替换
//		$str = str_replace(' ', '', $str);
//		$str = str_replace('$$$', "<br/>", $str);
//		dump($str);
//		echo $str; 
//		exit;
		
		//转换为GBK编码
		//$str = iconv("UTF-8","GBK",$str);
		 
		//输出
		ob_end_clean();//清除缓冲区,避免乱码
		header('Content-Length: '.strlen($str));
		header("content-Type:text/html; charset=gbk");
		header("Content-type:application/vnd.ms-excel");
		header("Content-Disposition:filename={$file_name}.xls");
		echo $str;
	}
}
?>